package com.windoent.yugioh.utils;

import android.text.InputFilter;
import android.text.Spanned;
import android.widget.EditText;

import com.zhy.http.okhttp.callback.StringCallback;

/**
 * author : robert
 * date   : 2021/5/31 11:19
 * desc   :限制字符
 */
public class EditLimitStringUtils {
    /**
     * 提示输入内容超过规定长度
     */
    public static void lengthFilter(EditText editText,
                                    final int max_length, final String err_msg) {

        InputFilter[] filters = new InputFilter[1];
        filters[0] = new InputFilter.LengthFilter(max_length) {

            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                // TODO Auto-generated method stub
                //获取字符个数
                int length = getLength(dest.toString());
                int slength = getLength(source.toString());
                if (length + slength > max_length) {
                    ToastUtils.showText(err_msg);
                    return "";
                }
                return source;

            }

        };
        editText.setFilters(filters);
    }

    private static int getLength(String content) {
        if (content.equals("") || null == content) {
            return 0;
        } else {
            return content.length();
        }
    }

    private static int getCharacterNum(String content) {
        if (content.equals("") || null == content) {
            return 0;
        } else {
            return content.length() + getChineseNum(content);
        }

    }

    /**
     * 计算字符串的中文长度
     */
    private static int getChineseNum(String s) {
        int num = 0;
        char[] myChar = s.toCharArray();
        for (int i = 0; i < myChar.length; i++) {
            if ((char) (byte) myChar[i] != myChar[i]) {
                num++;
            }
        }
        return num;
    }

}
